package com.borun.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.borun.dao.WordRepository;
import com.borun.entity.WordBaseBean;
import com.borun.entity.WordBean;
import com.borun.entity.condition.WordCondition;
import com.borun.service.WordService;

@Service
public class WordServiceImpl implements WordService{

	@Autowired
	private WordRepository wordRepository;
	
	@Override
	public Page<WordBean> getAll(int pageIndex, int pageSize) {
		return wordRepository.findAll(new PageRequest(pageIndex - 1, pageSize));
	}

	@Override
	public Page<WordBean> getByCondition(WordCondition wordCondition) {
		return wordRepository.findByCondition(wordCondition.getChinese(), wordCondition.getEnglish(), new PageRequest(wordCondition.getPageIndex(), wordCondition.getPageSize()));
	}

	@Override
	public WordBean getDetail(Integer id) {
		return wordRepository.findOne(id);
	}

	@Override
	public WordBean findByEnglish(String english) {
		return wordRepository.findDistinctByEnglish(english);
	}

	@Override
	public WordBean getWord(WordBean wordBean) {
		if(wordBean.getId() != 0)
			return wordRepository.findOne(wordBean.getId());
		else if(wordBean.getEnglish() != null)
			return wordRepository.findDistinctByEnglish(wordBean.getEnglish());
		else 
			return null;
	}

	@Override
	public WordBean saveOrupdate(WordBean wordBean) {
		return wordRepository.saveAndFlush(wordBean);
	}

	@Override
	public void delete(Integer id) {
		if(id != null && id > 0)
			wordRepository.delete(id);
	}

	@Override
	public void delete(List<Integer> ids) {
		if(ids != null && ids.size() > 0)
			for (Integer id:ids)
				delete(id);
	}

	@Override
	public Page<WordBean> findByWordBase(WordBaseBean wordBaseBean,
			Pageable pageable) {
		return wordRepository.findWordBeansByWordBaseBean(wordBaseBean, pageable);
	}

	@Override
	public Page<WordBean> findByWordBase(WordBaseBean wordBaseBean,
			int pageIndex, int pageSize) {
		return findByWordBase(wordBaseBean,new PageRequest(pageIndex, pageSize));
	}

	@Override
	public Page<WordBean> findByWordBase(Integer wordBaseId, int pageIndex,
			int pageSize) {
		return findByWordBase(new WordBaseBean(wordBaseId),new PageRequest(pageIndex, pageSize));
	}

	@Override
	public Page<WordBean> findByWordBase(Integer wordBaseId, Pageable pageable) {
		return findByWordBase(new WordBaseBean(wordBaseId),pageable);
	}

	@Override
	public List<WordBean> findByWordBase(Integer wordBaseId) {
		return wordRepository.findWordBeansByWordBaseBean(new WordBaseBean(wordBaseId));
	}


}
